package com.LeeCode;

/**
 * 城墙防线
 */

public class CodeLCP078 {
    public static void main(String[] args) {
        int[][] rampart = {
                {0, 3},
                {4, 5},
                {7, 9}
        };
        System.out.println(new CodeLCP078().rampartDefensiveLine(rampart));
    }

    public int rampartDefensiveLine(int[][] rampart) {
        int[] space = new int[rampart.length - 1];
        int left = 0, right = Integer.MAX_VALUE;
        for (int i = 0; i < space.length; i++) {
            space[i] = rampart[i + 1][0] - rampart[i][1];
            if (i == 0) continue;
            right = Math.min(right, space[i] + space[i - 1] + 1);
        }
        while (left + 1 < right) {
            int mid = left + (right - left) / 2;
            if (check(space, mid))
                left = mid;
            else
                right = mid;
        }
        return left;
    }

    private boolean check(int[] space, int out) {
        int leftUse = Math.min(space[0], out);
        for (int i = 0; i < space.length - 1; i++) {
            int rightNeed = out - leftUse;
            if (space[i + 1] < rightNeed) {
                return false;
            }
            leftUse = Math.min(space[i + 1] - rightNeed, out);
        }
        return true;
    }
}
